package com.orange.adminapi.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.adminapi.pojo.rsp.admin.AdminLoginRsp;
import com.orange.core.pojo.R;
import com.orange.core.security.detail.AdminDetail;
import com.orange.core.util.Constants;
import com.orange.core.util.IpUtil;
import com.orange.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        log.info("账号：{}登录成功，登录ip：{}", authentication.getName(), IpUtil.getRemoteIp(request));
        ((AbstractAuthenticationToken) authentication).eraseCredentials();

        // 记录token
        String token = TokenUtil.getToken(request, true);

        AdminDetail details = (AdminDetail) authentication.getPrincipal();
        AdminLoginRsp adminLoginRsp = new AdminLoginRsp().setId(details.getId()).setLoginName(details.getUsername())
                .setRoles(details.getRoles()).setPermissions(details.getPermissions());

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader(Constants.TOKEN_KEY, token);
        response.setBufferSize(10240);
        response.getWriter().write(objectMapper.writeValueAsString(R.ok(adminLoginRsp)));
    }
}
